package Com.Ring.TradingMobile;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import Com.Ring.TradingMobile.Lib.Common;
import Com.Ring.TradingMobile.Lib.RET_CODE;
import Com.Ring.TradingMobile.Lib.Session;
import Com.Ring.TradingMobile.Object.DanhMuc;
import Com.Ring.TradingMobile.Object.StockBalance;
import Com.Ring.TradingMobile.SQLite.DBManager;
import Com.Ring.TradingMobile.Service.WebService;
import android.R.integer;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class DanhMucActivity extends ListActivity {

	private DanhMucAdapter dmAdapter;
	private Button btnThemDanhMuc;
	private Button btnBack;
	private EditText txtTenDanhMuc;
	
	StringBuilder str = new StringBuilder();
	List<String> dsXoa = new ArrayList<String>();
	private DBManager dbData;
	private List<String> listDanhMuc = new ArrayList<String>();
	private String DanhMucSelected = "";
	private static final String TAG = "DanhMucActivityDebug";
	private static final int ENTER_SUA_DANH_MUC = 4;
	private DanhMucAsyncTask danhMucAsyncTask;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.danhmuc);
		Log.d(TAG, "On Create");
		InitControl();
		ControlsListen();
	}
	
	

	
	@Override
	protected void onPause() {
		dbData.close();
		Log.d(TAG, "On Pause");
		super.onPause();
	}

	@Override
	protected void onStart() {
		dbData = new DBManager(this);
		GetData();
		dmAdapter = new DanhMucAdapter(this);
		setListAdapter(dmAdapter);
		Log.d(TAG, "On Start");
		super.onStart();
	}

	@Override
	protected void onDestroy() {
		Log.d(TAG, "On Destroy");
		super.onDestroy();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		Log.d(TAG, "On Restart");
		super.onRestart();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		Log.d(TAG, "On Resume");
		super.onResume();
	}

	@Override
	protected void onStop() {
		Log.d(TAG, "On Stop");
		dbData.close();
		super.onStop();
	}

	private void InitControl() {
		btnThemDanhMuc = (Button) findViewById(R.id.btnThemDanhMuc);
		txtTenDanhMuc = (EditText) findViewById(R.id.txtTenDanhMuc);
		btnBack = (Button) findViewById(R.id.btnBack);
	}
	
	private void ControlsListen() {
		btnThemDanhMuc.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String txtTen = txtTenDanhMuc.getText().toString().trim();
				if (!txtTen.equals("")) {
					if(listDanhMuc.contains(txtTen))
						Toast.makeText(DanhMucActivity.this, getResources().getString(R.string.str_existdanhmuc), Toast.LENGTH_SHORT).show();
					else {
						txtTenDanhMuc.setText("");
						AddDanhMuc(txtTen);
						LoadDanhMucAsync();
					}
				}
			}
		});
		btnBack.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case ENTER_SUA_DANH_MUC:
			LayoutInflater factoryEnterSua = LayoutInflater.from(this);
			final View EnterSuaView = factoryEnterSua.inflate(
					R.layout.dialog_danhmuc, null);
			EditText txt = (EditText) EnterSuaView
					.findViewById(R.id.editTenDanhMuc);
			txt.setText(DanhMucSelected);
			AlertDialog.Builder builderEnterSua = new AlertDialog.Builder(
					DanhMucActivity.this);
			builderEnterSua.setIcon(R.drawable.alert_dialog_icon);
			builderEnterSua.setTitle("Sửa Danh Mục");
			builderEnterSua.setView(EnterSuaView);
			builderEnterSua.setPositiveButton(R.string.str_ok,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							EditText txt = (EditText) EnterSuaView
									.findViewById(R.id.editTenDanhMuc);
							if(!txt.getText().toString().equals(DanhMucSelected)) {
								UpdateDanhMuc(txt.getText().toString(),DanhMucSelected);
								LoadDanhMucAsync();
							}
							txt.setText("");
							removeDialog(ENTER_SUA_DANH_MUC);
						}
					});

			builderEnterSua.setNegativeButton(R.string.str_cancel,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							removeDialog(ENTER_SUA_DANH_MUC);
						}
					});
			return builderEnterSua.create();
		}
		return null;
	}

	private void RefreshAdapter() {
		GetData();
		dmAdapter = new DanhMucAdapter(this);
		setListAdapter(dmAdapter);
	}
	
	

	private void GetData() {
		if(!Session.IsLogin) {
			Cursor CursorGlobal = dbData.Select("select * from "
					+ DanhMuc.TABLE_NAME);
			if (CursorGlobal != null && CursorGlobal.getCount() > 0) {
				int count = CursorGlobal.getCount();
				listDanhMuc.clear();
				for (int i = 0; i < count; i++) {
					CursorGlobal.moveToPosition(i);
					String string = CursorGlobal.getString(CursorGlobal
							.getColumnIndex(DanhMuc.NAME_DANH_MUC));
					listDanhMuc.add(string);
				}
				CursorGlobal.close();
			}
		}else {
			GetListDanhMuc(Session.subCustAccounts.get(0));
		}
	}
	
	private void GetListDanhMuc(String subAccount) {
		SoapObject request = new SoapObject(WebService.NAMESPACE,
				WebService.GetListDanhMuc);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		PropertyInfo parAccountNo = new PropertyInfo();
		parAccountNo.setName("accountNo");
		parAccountNo.setValue(subAccount);
		parAccountNo.setNamespace(WebService.NAMESPACE);
		request.addProperty(parAccountNo);

		envelope.setOutputSoapObject(request);
		HttpTransportSE http = new HttpTransportSE(
				WebService.ADDRESS_RTSERVICE);
		String soapAction = WebService.NAMESPACE + WebService.GetListDanhMuc;

		try {
			http.call(soapAction, envelope);
			JSONObject resultsObj = new JSONObject(envelope.getResponse()
					.toString());
			int retCode;
			if (resultsObj != null) {
				retCode = resultsObj.getInt("RetCode");
				if (retCode == RET_CODE.SUCCESS.Value) {
					JSONArray danhMucArray = resultsObj.getJSONArray("Result");
					if(danhMucArray.length()>0)
						listDanhMuc.clear();
					for (int i = 0; i < danhMucArray.length(); i++) {
						JSONObject jsonObject = danhMucArray.getJSONObject(i);
						String data = jsonObject.getString("NameDanhMuc");
						if(!data.equals("") || !data.equals("null"))
							listDanhMuc.add(data);
					}
				}
			}
		} catch (Exception ex) {
			Log.d(TAG, ex.toString());
		}
	}
	
	private void AddDanhMuc(String nameDanhMuc) {
		if(!Session.IsLogin) {
			dbData.InsertDanhMuc(nameDanhMuc);
			txtTenDanhMuc.setText("");
		}else {
			SoapObject request = new SoapObject(WebService.NAMESPACE,
					WebService.AddDanhMuc);
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			PropertyInfo parAccountNo = new PropertyInfo();
			parAccountNo.setName("accountNo");
			parAccountNo.setValue(Session.subCustAccounts.get(0));
			parAccountNo.setNamespace(WebService.NAMESPACE);
			PropertyInfo parnameDanhMuc = new PropertyInfo();
			parnameDanhMuc.setName("nameDanhMuc");
			parnameDanhMuc.setValue(nameDanhMuc);
			parnameDanhMuc.setNamespace(WebService.NAMESPACE);
			
			request.addProperty(parAccountNo);
			request.addProperty(parnameDanhMuc);

			envelope.setOutputSoapObject(request);
			HttpTransportSE http = new HttpTransportSE(
					WebService.ADDRESS_RTSERVICE);
			String soapAction = WebService.NAMESPACE + WebService.AddDanhMuc;
			try {
				http.call(soapAction, envelope);
			} catch (Exception ex) {
				Log.d(TAG, ex.toString());
			}
		}
		
	}
	
	private void DeleteDanhMuc() {
		if(!Session.IsLogin)
			dbData.DeleteDanhMuc(dsXoa.toArray());
		else {
			SoapObject request = new SoapObject(WebService.NAMESPACE,
					WebService.DeleteDanhMuc);
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			PropertyInfo parAccountNo = new PropertyInfo();
			parAccountNo.setName("accountNo");
			parAccountNo.setValue(Session.subCustAccounts.get(0));
			parAccountNo.setNamespace(WebService.NAMESPACE);
			PropertyInfo parnameDanhMuc = new PropertyInfo();
			parnameDanhMuc.setName("nameDanhMuc");
			parnameDanhMuc.setValue(dsXoa.get(0));
			parnameDanhMuc.setNamespace(WebService.NAMESPACE);
			
			request.addProperty(parAccountNo);
			request.addProperty(parnameDanhMuc);

			envelope.setOutputSoapObject(request);
			HttpTransportSE http = new HttpTransportSE(
					WebService.ADDRESS_RTSERVICE);
			String soapAction = WebService.NAMESPACE + WebService.DeleteDanhMuc;
			try {
				http.call(soapAction, envelope);
			} catch (Exception ex) {
				Log.d(TAG, ex.toString());
			}
		}
	}
	
	private void UpdateDanhMuc(String strNew,String strOld) {
		if(!Session.IsLogin)
		dbData.UpdateDanhMuc(strNew,strOld);
		else {
			SoapObject request = new SoapObject(WebService.NAMESPACE,
					WebService.UpdateDanhMuc);
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			PropertyInfo parAccountNo = new PropertyInfo();
			parAccountNo.setName("accountNo");
			parAccountNo.setValue(Session.subCustAccounts.get(0));
			parAccountNo.setNamespace(WebService.NAMESPACE);
			PropertyInfo parnameDanhMucNew = new PropertyInfo();
			parnameDanhMucNew.setName("nameDanhMucNew");
			parnameDanhMucNew.setValue(strNew);
			parnameDanhMucNew.setNamespace(WebService.NAMESPACE);
			PropertyInfo parnameDanhMucOld = new PropertyInfo();
			parnameDanhMucOld.setName("nameDanhMucOld");
			parnameDanhMucOld.setValue(strOld);
			parnameDanhMucOld.setNamespace(WebService.NAMESPACE);
			request.addProperty(parAccountNo);
			request.addProperty(parnameDanhMucNew);
			request.addProperty(parnameDanhMucOld);

			envelope.setOutputSoapObject(request);
			HttpTransportSE http = new HttpTransportSE(
					WebService.ADDRESS_RTSERVICE);
			String soapAction = WebService.NAMESPACE + WebService.UpdateDanhMuc;
			try {
				http.call(soapAction, envelope);
			} catch (Exception ex) {
				Log.d(TAG, ex.toString());
			}
		}
	}

	private class DanhMucAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public DanhMucAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
		}

		public int getCount() {
			return listDanhMuc.size();
		}

		public Object getItem(int arg0) {
			return arg0;
		}

		public long getItemId(int arg0) {

			return arg0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			final int pos = position;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.list_custom_danhmuc,
						null);
				holder = new ViewHolder();
				holder.txtDanhMuc = (TextView) convertView
						.findViewById(R.id.lblDanhMuc);
				holder.btnDel = (Button) convertView
						.findViewById(R.id.btnXoaDM);
				holder.btnEdit = (Button) convertView
						.findViewById(R.id.btn_SuaDM);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			
			convertView.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(v.getContext(), ThiTruongActivity.class);
					Bundle senderBundle = new Bundle();
					senderBundle.putStringArray(Common.KeyIntentThiTruong, new String[] {
							"1", listDanhMuc.get(pos), "1" });
					intent.putExtras(senderBundle);
					startActivity(intent);
				}
			});

			holder.txtDanhMuc.setText(listDanhMuc.get(position));
			
			holder.btnDel.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					AlertDialog.Builder builderXoa = new Builder(
							DanhMucActivity.this);
					builderXoa.setIcon(R.drawable.alert_dialog_icon);
					builderXoa.setTitle(R.string.strCofirmXoa);
					builderXoa.setPositiveButton(R.string.str_ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									dsXoa.clear();
									dsXoa.add(listDanhMuc.get(pos));
									DeleteDanhMuc();
									LoadDanhMucAsync();
								}
							});
					builderXoa.setNegativeButton(R.string.str_cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
								}
							});
					builderXoa.show();
				}
			});
			holder.btnEdit.setOnClickListener(new OnClickListener() {

				public void onClick(View arg0) {
					DanhMucSelected = listDanhMuc.get(pos);
					showDialog(ENTER_SUA_DANH_MUC);
				}
			});
			if(listDanhMuc.get(pos).equals(Common.DanhMucRoot))
			{
				holder.btnDel.setEnabled(false);
				holder.btnEdit.setEnabled(false);
			}
			return convertView;
		}

		class ViewHolder {
			Button btnDel;
			Button btnEdit;
			TextView txtDanhMuc;
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.ListActivity#onListItemClick(android.widget.ListView,
	 * android.view.View, int, long)
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		TextView txt = (TextView) v;
		Intent intent = new Intent(v.getContext(), ThiTruongActivity.class);
		Bundle senderBundle = new Bundle();
		senderBundle.putStringArray(Common.KeyIntentThiTruong, new String[] {
				"1", txt.getText().toString(), "1" });
		intent.putExtras(senderBundle);
		startActivity(intent);
	}
	
	private class DanhMucAsyncTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			GetData();
			return null;
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(Void result) {
			dmAdapter = new DanhMucAdapter(DanhMucActivity.this);
			setListAdapter(dmAdapter);
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}
		
	}
	private void CancelLoadDanhMucAsync() {
		if(danhMucAsyncTask!=null) {
			danhMucAsyncTask.cancel(true);
			danhMucAsyncTask=null;
		}
	}
	private void LoadDanhMucAsync() {
		CancelLoadDanhMucAsync();
		danhMucAsyncTask = new DanhMucAsyncTask();
		danhMucAsyncTask.execute();
	}
}
